

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Globalization;
using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Localization;
using JTC.MiniCommerce.Store;
using JTC.MiniCommerce.Store.Web.Controls;
using SubSonic.Utilities;

namespace JTC.MiniCommerce.Web.admin.controls.product {
  public partial class general : AdminControl {

    #region Constants

    private const string CONTENT_PATH = @"~/repository/content/";

    #endregion  

    #region Member Variables
    
    private int productId = 0;
    private string view = string.Empty;
    private Product product;
    
    #endregion
    
    #region Page Events

    /// <summary>
    /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event.
    /// </summary>
    /// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
    protected override void OnInit(EventArgs e) {
      Session["FCKeditor:UserFilesPath"] = CONTENT_PATH;
      base.OnInit(e);
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      try {
        productId = Utility.GetIntParameter("productId");
        view = Utility.GetParameter("view");
        if (view == "g") {
          SetGeneralProperties();
          SiteSettings siteSettings = SiteSettings.Load();
          if (productId > 0) {
            product = new Product(productId);
          }
          else {
            product = new Product();
          }

          if (!Page.IsPostBack) {
            LoadManufacturer();
            LoadProductStatus();
            LoadProductType();
            LoadShippingEstimate();

            txtBaseSku.Text = product.BaseSku;
            txtName.Text = product.Name;
            txtShortDescription.Value = HttpUtility.HtmlDecode(product.ShortDescription);
            txtOurPrice.Text = StoreUtility.GetFormattedAmount(product.OurPrice, false);
            txtRetailPrice.Text = StoreUtility.GetFormattedAmount(product.RetailPrice, false);
            ddlManufacturer.SelectedValue = product.ManufacturerId.ToString();
            ddlStatus.SelectedValue = product.StatusId.ToString();
            ddlProductType.SelectedValue = product.ProductTypeId.ToString();
            ddlShippingEstimate.SelectedValue = product.ShippingEstimateId.ToString();
            txtWeight.Text = product.Weight.ToString();
            txtLength.Text = product.Length.ToString();
            txtHeight.Text = product.Height.ToString();
            txtWidth.Text = product.Width.ToString();
          }
          lblOurPriceCurrencySymbol.Text = siteSettings.CurrencySymbol;
          lblRetailPriceCurrencySymbol.Text = siteSettings.CurrencySymbol;
        }
      }
      catch (Exception ex) {
        Logger.Error(typeof(general).Name + ".Page_Load", ex);
        base.MasterPage.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnManufacturerAdd control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnManufacturerAdd_Click(object sender, EventArgs e) {
      try {
        if(!string.IsNullOrEmpty(txtManufacturerAdd.Text)) {
          Manufacturer manufacturer = new Manufacturer();
          manufacturer.Name = txtManufacturerAdd.Text.Trim();
          manufacturer.Save(WebUtility.GetUserName());
          txtManufacturerAdd.Text = string.Empty;
          LoadManufacturer();
          ddlManufacturer.SelectedIndex = ddlManufacturer.Items.Count - 1;
        }
      }
      catch (Exception ex) {
        Logger.Error(typeof(general).Name + ".btnManufacturerAdd_Click", ex);
        throw;
      }
    }

    /// <summary>
    /// Handles the Click event of the btnProductTypeAdd control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnProductTypeAdd_Click(object sender, EventArgs e) {
      try {
        if (!string.IsNullOrEmpty(txtProductTypeAdd.Text)) {
          ProductType productType = new ProductType();
          productType.Name = txtProductTypeAdd.Text.Trim();
          productType.Save(WebUtility.GetUserName());
          txtProductTypeAdd.Text = string.Empty;
          LoadProductType();
          ddlProductType.SelectedIndex = ddlProductType.Items.Count - 1;
        }
      }
      catch (Exception ex) {
        Logger.Error(typeof(general).Name + ".btnProductTypeAdd_Click", ex);
        throw;
      }
    }

    /// <summary>
    /// Handles the Click event of the btnSave control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
      if(Page.IsValid) {
        try {
          int manufacturerId = 0;
          int.TryParse(ddlManufacturer.SelectedValue, out manufacturerId);
          int statusId = 0;
          int.TryParse(ddlStatus.SelectedValue, out statusId);
          int productTypeId = 0;
          int.TryParse(ddlProductType.SelectedValue, out productTypeId);
          int shippingEstimateId = 0;
          int.TryParse(ddlShippingEstimate.SelectedValue, out shippingEstimateId);

          decimal ourPrice = 0;
          decimal.TryParse(txtOurPrice.Text.Trim(), out ourPrice);
          decimal retailPrice = 0;
          decimal.TryParse(txtRetailPrice.Text.Trim(), out retailPrice);
          decimal weight = 0;
          decimal.TryParse(txtWeight.Text.Trim(), out weight);
          decimal length = 0;
          decimal.TryParse(txtLength.Text.Trim(), out length);
          decimal height = 0;
          decimal.TryParse(txtHeight.Text.Trim(), out height);
          decimal width = 0;
          decimal.TryParse(txtWidth.Text.Trim(), out width);
          //int listOrder = 0;
          //int.TryParse(txtListOrder.Text.Trim(), out listOrder);
          if(product.ProductId == 0) {
            product.ProductGuid = new Guid();
          }
          product.BaseSku = txtBaseSku.Text.Trim();
          product.Name = txtName.Text.Trim();
          product.ShortDescription = HttpUtility.HtmlEncode(txtShortDescription.Value.Trim());
          product.OurPrice = ourPrice;
          product.RetailPrice = retailPrice;
          product.ManufacturerId = manufacturerId;
          product.StatusId = statusId;
          product.ProductTypeId = productTypeId;
          product.ShippingEstimateId = shippingEstimateId;
          product.Weight = weight;
          product.Length = length;
          product.Height = height;
          product.Width = width;
          //default this to avoid division errors
          product.TotalRatingVotes = 1;
          product.RatingSum = 3;
          product.Save(WebUtility.GetUserName());
          if(product.ProductId > 0) {
            Response.Redirect(string.Format("~/admin/productedit.aspx?view=g&productId={0}", product.ProductId.ToString()), true);
          }
          else {
            base.MasterPage.MessageCenter.DisplayFailureMessage(LocalizationUtility.GetText("lblProductNotSaved"));
          }
        }
        catch(Exception ex) {
          Logger.Error(typeof(general).Name + ".btnSave_Click", ex);
          base.MasterPage.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
        }
      }
    }
    
    #endregion
    
    #region Methods
    
    #region Private

    /// <summary>
    /// Sets the general properties.
    /// </summary>
    private void SetGeneralProperties () {
      LocalizationUtility.AddPanelText(pnlGeneralProductInformation);
      LocalizationUtility.AddLabelText(lblBaseSku);
      LocalizationUtility.AddHoverHelp(hlBaseSkuHelp);
      LocalizationUtility.AddLabelText(lblName);
      LocalizationUtility.AddHoverHelp(hlNameHelp);
      LocalizationUtility.AddLabelText(lblShortDescription);
      LocalizationUtility.AddHoverHelp(hlShortDescriptionHelp);
      LocalizationUtility.AddLabelText(lblOurPrice);
      LocalizationUtility.AddHoverHelp(hlOurPriceHelp);
      LocalizationUtility.AddLabelText(lblRetailPrice);
      LocalizationUtility.AddHoverHelp(hlRetailPriceHelp);
      LocalizationUtility.AddLabelText(lblManufacturer);
      LocalizationUtility.AddHoverHelp(hlManufacturerHelp);
      LocalizationUtility.AddButtonText(btnManufacturerAdd);
      LocalizationUtility.AddLabelText(lblStatus);
      LocalizationUtility.AddHoverHelp(hlStatusHelp);
      LocalizationUtility.AddLabelText(lblProductType);
      LocalizationUtility.AddHoverHelp(hlProductTypeHelp);
      LocalizationUtility.AddButtonText(btnProductTypeAdd);
      LocalizationUtility.AddLabelText(lblShippingEstimate);
      LocalizationUtility.AddHoverHelp(hlShippingEstimateHelp);
      LocalizationUtility.AddLabelText(lblWeight);
      LocalizationUtility.AddHoverHelp(hlWeightHelp);
      LocalizationUtility.AddLabelText(lblDimensions);
      LocalizationUtility.AddLabelText(lblLength);
      LocalizationUtility.AddHoverHelp(hlProductLengthHelp);
      LocalizationUtility.AddLabelText(lblHeight);
      LocalizationUtility.AddHoverHelp(hlProductHeightHelp);
      LocalizationUtility.AddLabelText(lblWidth);
      LocalizationUtility.AddHoverHelp(hlProductWidthHelp);
      LocalizationUtility.AddButtonText(btnSave);
    }

    /// <summary>
    /// Loads the shipping estimate.
    /// </summary>
    private void LoadShippingEstimate () {
      ShippingEstimateCollection shippingEstimateCollection = new ShippingEstimateController().FetchAll();
      shippingEstimateCollection.OrderByAsc(ShippingEstimate.Columns.Name);
      ddlShippingEstimate.DataSource = shippingEstimateCollection;
      ddlShippingEstimate.DataTextField = ShippingEstimate.Columns.Name;
      ddlShippingEstimate.DataValueField = ShippingEstimate.Columns.ShippingEstimateId;
      ddlShippingEstimate.DataBind();
      ddlShippingEstimate.SelectedValue = product.ShippingEstimateId.ToString();
    }

    /// <summary>
    /// Loads the manufacturer.
    /// </summary>
    private void LoadManufacturer () {
      ManufacturerCollection manufacturerCollection = new ManufacturerController().FetchAll();
      manufacturerCollection.OrderByAsc(Manufacturer.Columns.Name);
      ddlManufacturer.DataSource = manufacturerCollection;
      ddlManufacturer.DataTextField = Manufacturer.Columns.Name;
      ddlManufacturer.DataValueField = Manufacturer.Columns.ManufacturerId;
      ddlManufacturer.DataBind();
    }

    /// <summary>
    /// Loads the product status.
    /// </summary>
    private void LoadProductStatus () {
      ProductStatusDescriptorCollection productStatusDescriptorCollection = new ProductStatusDescriptorController().FetchAll();
      productStatusDescriptorCollection.OrderByAsc(ProductStatusDescriptor.Columns.Name);
      ddlStatus.DataSource = productStatusDescriptorCollection;
      ddlStatus.DataTextField = ProductStatusDescriptor.Columns.Name;
      ddlStatus.DataValueField = ProductStatusDescriptor.Columns.StatusId;
      ddlStatus.DataBind();
      ddlStatus.SelectedValue = product.StatusId.ToString();
    }

    /// <summary>
    /// Loads the type of the product.
    /// </summary>
    private void LoadProductType () {
      ProductTypeCollection productTypeCollection = new ProductTypeController().FetchAll();
      productTypeCollection.OrderByAsc(ProductType.Columns.Name);
      ddlProductType.DataSource = productTypeCollection;
      ddlProductType.DataTextField = ProductType.Columns.Name;
      ddlProductType.DataValueField = ProductType.Columns.ProductTypeId;
      ddlProductType.DataBind();
    }
    
    #endregion
    
    #endregion
    
  }
}